package com.magic.blog.schedules;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.magic.blog.entity.MPost;
import com.magic.blog.service.MPostService;
import com.magic.blog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class ViewCountsSyncTask {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MPostService postService;

    @Scheduled(cron = "0/5 * * * * *")//每5秒同步一次
    public void task() {
        Set<String> keys = redisTemplate.keys("rank:post:*");
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if (redisUtil.hHasKey(key, "post:viewCount")) {
                ids.add(key.substring("rank:post:".length()));
            }
        }

        if (ids.isEmpty()) {
            return;
        }

        //需要更新的阅读量
        List<MPost> posts = postService.list(new QueryWrapper<MPost>().in("id", ids));

        posts.stream().forEach((post) -> {
            Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        });

        if (posts.isEmpty()) {
            return;
        }

        boolean isSuccess = postService.updateBatchById(posts);


        if (isSuccess) {
            ids.stream().forEach((id) -> {
                redisUtil.hdel("rank:post:" + id, "post:viewCount");//清除缓存

                System.out.println(id + "同步成功");
            });

        }
    }
}
